package com.njupt.user.controller;


import com.njupt.user.model.*;
import com.njupt.user.service.*;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class UserController {

    private int thispage;
    private int lastpages;
    private String likevalue;
    private String type;
    private FileSend fs = new FileSend();
    private static Logger logger = org.apache.log4j.Logger.getLogger(UserController.class);


    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public int getThispage() {
        return thispage;
    }

    public void setThispage(int thispage) {
        this.thispage = thispage;
    }

    public int getLastpages() {
        return lastpages;
    }

    public void setLastpages(int lastpages) {
        this.lastpages = lastpages;
    }

    public String getLikevalue() {
        return likevalue;
    }

    public void setLikevalue(String likevalue) {
        this.likevalue = likevalue;
    }

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }


    @Autowired
    private TestFlieService testFlieService;
    @Autowired
    private UserService userService;
    @Autowired
    private GradeService gradeService;
    @Autowired
    private OrderTestService orderTestService;
    @Autowired
    private deviceService deviceService;


    /*
    *学生用户页面头部的跳转
     *
    */

    @RequestMapping("jump")
    public ModelAndView jump(ModelAndView mv,
                             @RequestParam("name") String name,
                             @RequestParam("username") String username,
                             HttpSession session) {
        System.out.println("1111");
        session.setAttribute("username", username);
        mv.setViewName(name);
        return mv;
    }

    /*
     *学生用户页面实验功能的跳转
    *
    */
    @RequestMapping("jumpTest")
    public ModelAndView jumpTest(ModelAndView mv,
                                 @RequestParam("name") String name,
                                 @RequestParam("username") String username,
                                 @RequestParam("test_name") String test_name,
                                 HttpSession session) {
        if (name.endsWith("video")) {
            session.setAttribute("username", username);
            session.setAttribute("test_name", test_name);
            mv.setViewName(name);
        } else if (name.endsWith("document")) {
            session.setAttribute("username", username);
            session.setAttribute("test_name", test_name);
            mv.setViewName(name);
        } else {
            session.setAttribute("username", username);
            session.setAttribute("test_name", test_name);
            mv.setViewName(name);
        }
        return mv;
    }

    @RequestMapping("fileUpload")
    public ModelAndView dotest(ModelAndView mv,
                               @RequestParam("username") String username,
                               @RequestParam("test_name") String test_name,
                               @RequestParam("test") String test,
                               @RequestParam("id") String id,
                               @RequestParam("uploadfile") List<MultipartFile> uploadfile,
                               HttpSession session) {
        // 判断所上传文件是否存在
        if (!uploadfile.isEmpty() && uploadfile.size() > 0) {
            //循环输出上传的文件
            for (MultipartFile file : uploadfile) {
                // 获取上传文件的原始名称
                String originalFilename = file.getOriginalFilename();
                // 设置上传文件的保存地址目录
                //               String dirPath =
                //                     request.getSession().getServletContext().getRealPath("/upload/");
                String dirPath = "e:/upload/user/"+username+"/";
//                String dirPath =
                //                       request.getServletContext().getRealPath("/upload/");
                File filePath = new File(dirPath);
                // 如果保存文件的地址不存在，就先创建目录
                if (!filePath.exists()) {
                    filePath.mkdirs();
                }
//                String newFilename = username+ "_"+originalFilename;
                try {
                    // 使用MultipartFile接口的方法完成文件上传到指定位置
                    file.transferTo(new File(dirPath + originalFilename));
                } catch (Exception e) {
                    e.printStackTrace();
                    session.setAttribute("username", username);
                    session.setAttribute("test_name", test_name);
                    mv.setViewName("error");
                }

                FileWriter writer = null;
                try {
                    writer = new FileWriter("e://upload//record//record.txt",true);
                    writer.write(dirPath+originalFilename+"\r\n");
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            // 跳转到成功页面
            session.setAttribute("username", username);
            session.setAttribute("test_name", test_name);
            mv.addObject("test",test);
            mv.addObject("id",id);
            mv.setViewName("success");
        }else{
            session.setAttribute("username", username);
            session.setAttribute("test_name", test_name);
            mv.setViewName("error");
        }
        return mv;
    }

    @RequestMapping("filedone")
    public ModelAndView filedone(ModelAndView mv,
                                    @RequestParam("username") String username,
                                    @RequestParam("test_name") String test_name,
                                    HttpSession session) {
        mv.setViewName("success");
        return mv;
    }

    @RequestMapping("submit_test")
    public ModelAndView submit_test(ModelAndView mv,
                                    @RequestParam("name") String name,
                                    @RequestParam("username") String username,
                                    @RequestParam("test_name") String test_name,
                                    HttpSession session) {
        //建表，判断是否提交过lognimsg3
        List<String> orderLsit = orderTestService.selectBoxnoBynow();
        String testno = String.valueOf(FPGACount.usestu.get(username));
        if(orderLsit.contains(testno)){
            FPGACount.inuse.remove(testno);
            FPGACount.usestu.remove(username);
        }else {
            int tp = FPGACount.inuse.indexOf(testno);
            FPGACount.inuse.remove(tp);
            FPGACount.notuse.add(testno);
            FPGACount.usestu.remove(username);
        }
        TestFile testFile = new TestFile(username, test_name, "C:\\\\Users\\\\ASUS\\\\Desktop\\\\毕业设计\\\\njupt\\\\web\\\\upload\\\\" + username + "_" + test_name + ".txt");
        Map<String, String> map = new HashMap<String, String>();
        map.put("username", username);
        map.put("name_test", test_name);
        List test_file_list = testFlieService.selectTestFile(map);
        if (test_file_list.size() == 1) {
            System.out.println(1);
            session.setAttribute("lognimsg3", "已经提交过一次，请勿重复提交");
            mv.setViewName("success");
        } else {
            testFlieService.register(testFile);
            session.setAttribute("lognimsg3", "");
            logger.info(username + "上传了" + test_name + "实验文件");
            mv.setViewName(name);
        }
        return mv;
    }

    /*
    *学生退出
     *
    */
    @RequestMapping("finish")
    public ModelAndView finish_test(ModelAndView mv,
                                    @RequestParam("username") String username) {

        if (FPGACount.usestu.containsKey(username)) {
            List<String> orderLsit = orderTestService.selectBoxnoBynow();
            String testno = String.valueOf(FPGACount.usestu.get(username));
            if(orderLsit.contains(testno)){
                FPGACount.inuse.remove(testno);
                FPGACount.usestu.remove(username);
            }else {
                int tp = FPGACount.inuse.indexOf(testno);
                FPGACount.inuse.remove(tp);
                FPGACount.notuse.add(testno);
                FPGACount.usestu.remove(username);
            }
            mv.setViewName("fpga_login");
        } else {
            mv.setViewName("fpga_login");
        }
        return mv;
    }

    /*
   *查询成绩
    *
   */
    @RequestMapping("grade")
    public ModelAndView grade(ModelAndView mv,
                              @RequestParam("username") String username,
                              HttpSession session) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("username", username);
        System.out.println(username);
        List<Grade> list = gradeService.selectGrade(map);
        System.out.println(list.size());
        session.setAttribute("grades", list);
        session.setAttribute("username", username);
        mv.setViewName("fpga_grade");
        return mv;
    }

    /*
   * 登陆校验，需要检验账号密码是否正确，然后识别身份（老师或者用户）(ok)
   *
   */
    @RequestMapping("login")
    public ModelAndView login(ModelAndView mv,
                              @RequestParam("username") String username,
                              @RequestParam("password") String password,
                              HttpSession session) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("username", username);
        map.put("password", password);
        User user;
        user = userService.getUser(map);
        if (user != null) {
            if (user.getUsertype().equals("老师")) {
                session.setAttribute("user", user);
                session.setAttribute("username", username);
                mv.setViewName("fpga_teacher_main");
            } else {
                session.setAttribute("user", user);
                session.setAttribute("username", username);
                mv.setViewName("fpga_main");
            }
        } else {
            mv.addObject("message", "账号或密码错误！请重新输入");
            mv.setViewName("fpga_login");
    }
        System.out.println("结束登陆...");
        return mv;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    /*
     *密码找回模块
     */
    @RequestMapping("user_retrieve")
    public ModelAndView retrieve(ModelAndView mv,HttpServletRequest request) {
        String username = request.getParameter("username");
        String te = String.valueOf(request.getParameter("tel"));
        if(username==""||te==""){
            mv.setViewName("fpga_foundpwd");
            return mv;
        }
        else{
            long tel = Long.parseLong( te );
            Map map = new HashMap();
            map.put("username", username);
            map.put("tel", tel);
            User user = userService.retrieve(map);
//          System.out.println("kkkk"+user+"zzz");
            if (user== null) {
                mv.addObject("message", "对不起，信息输入错误，请重新输入");
                mv.setViewName("fpga_foundpwd");
                return mv;
            } else {
                request.setAttribute("message", "请牢记，您的密码为："+user.getPassword());
                mv.setViewName("fpga_login");
                return mv;
            }
        }

    }
    /*
     * 用户注册(ok)
     * 缺判断用户名、用户ID是否已存在？
     */
    @RequestMapping("deviceChoose")
    public ModelAndView deviceChoose(ModelAndView mv,HttpServletRequest request){
        String s1=request.getParameter("id");
        String s2=request.getParameter("test");
        Map<String, String> map = new HashMap<String, String>();
        map.put("id", s1);
        deviceService.updateDevice(map);
        mv.addObject("test",s2);
        mv.addObject("id",s1);
        mv.setViewName("fpga_test");
        return mv;
    }

    @RequestMapping("quitChoose")
    public ModelAndView quitChoose(ModelAndView mv,HttpServletRequest request){
        String s1=request.getParameter("id");
        Map<String, String> map = new HashMap<String, String>();
        map.put("id", s1);
        deviceService.quitDevice(map);
        mv.setViewName("fpga_main");
        return mv;
    }

    @RequestMapping("register")
    public ModelAndView register(ModelAndView mv,HttpServletRequest request) {
        String s1=""+request.getParameter("userid");
        String s2=request.getParameter("username");
        String s3=request.getParameter("password");
        String s4=""+request.getParameter("tel");
        String s5=request.getParameter("sex");
        String s6=""+request.getParameter("age");
        String s7="普通用户";

        if(s1==""||s2==""||s3==""||s4==""||s5==""||s6==""){
            mv.setViewName("fpga_register");
            return mv;
        }
        else{
            Map<String, String> map = new HashMap<String, String>();
            map.put("userid",request.getParameter("userid"));
            map.put("username", s2);
            map.put("password", s3);
            map.put("tel",request.getParameter("tel"));
            map.put("usertype",s7);
            map.put("sex",s5);
            map.put("age",request.getParameter("age"));
            userService.register(map);


            mv.setViewName("fpga_login");
            return mv;
        }

    }

    /*
    *注册去重
    *
    */
    @RequestMapping("CheckUser")
    public void checkUser(@RequestParam("username") String username,
                          HttpServletResponse resp) throws IOException {
        Map<String, String> map = new HashMap<String, String>();
        map.put("username", username);
        List list = userService.findUserByUsername(map);
        if (list.size() == 1) {
            resp.getWriter().print("0");
        } else {
            resp.getWriter().print("1");
        }
    }

    /*
    *预约实验
    *
    */
    @RequestMapping("orderTest")
    public ModelAndView orderTest(ModelAndView mv,
                                  @RequestParam("name") String name,
                                  @RequestParam("username") String username,
                                  HttpSession session) throws IOException {
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd ");
        Date dt = new Date();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(dt);
        calendar.add(calendar.DATE, 1);
        dt = calendar.getTime();
        session.setAttribute("date", ft.format(dt));
        session.setAttribute("username",username);
        session.setAttribute("msg","");
        mv.setViewName(name);
        return mv;
    }
    @RequestMapping("orderCheck")
    public ModelAndView orderCheck(ModelAndView mv,
                                  @RequestParam("ordertime") String time,
                                  HttpSession session) throws IOException {
        String username = (String) session.getAttribute("username");
        time = time.substring(0,11)+time.split("-")[3];
        Map<String, String> map = new HashMap<String, String>();
        map.put("date",time);
        map.put("username",username);
        List count = orderTestService.selectBoxnoByUsername(map);
//        System.out.println(map);
//        System.out.println(count);
        if(count.size()==1){
            session.setAttribute("msg","您已经预约过该时间段进行实验，请勿重复预约");
            session.setAttribute("date",time.substring(0,11));
            mv.setViewName("fpga_order");
            return mv;
        }
        List<String> list = orderTestService.selectBoxno(map);
        List list_bak = new ArrayList(FPGACount.total);
        list_bak.removeAll(list);
        if(list_bak.size()==0){
            session.setAttribute("msg","该时间段没有试验箱，请选择其他时间");
            session.setAttribute("date",time.substring(0,11));
            mv.setViewName("fpga_order");
            return mv;
        }
        map.put("boxno",(String) list_bak.get(0));
//        System.out.println(map);
        orderTestService.addOrder(map);
        mv.setViewName("fpga_upfile");
        return mv;
    }
    /*
     *登陆页面注册按钮跳转方法(ok)
     *
     */
    @RequestMapping("reg")
    public ModelAndView reg(ModelAndView mv)
    {
        mv.setViewName("fpga_register");
        return mv;
    }
    @RequestMapping("ind")
    public String ind() {
        return "fpga_index";
    }

    @RequestMapping("pwd")
    public String pwd() {
        return "fpga_foundpwd";
    }


    /*
     *查询用户信息
     * (selectUser页面读不到,用测试页面findUser页面)
     */
    @RequestMapping("findUser")
    public ModelAndView selectUser(ModelAndView mv,
                                   @RequestParam("username") String username) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("username", username);
        List<User> list =  userService.selectUser(map);
        mv.addObject("users",list);
        System.out.println(list);
        mv.setViewName("fpga_selectUser");
        return mv;
    }
    @RequestMapping("deviceStatus")
    public ModelAndView deviceStatus(ModelAndView mv,@RequestParam("username") String username) {
        Map<String, String> map1 = new HashMap<String, String>();
        map1.put("id", "1");
        Map<String, String> map2 = new HashMap<String, String>();
        map2.put("id", "2");
        Map<String, String> map3= new HashMap<String, String>();
        map3.put("id", "3");
        List<device> list1=deviceService.selectDevice(map1);
        List<device> list2=deviceService.selectDevice(map2);
        List<device> list3=deviceService.selectDevice(map3);

        mv.addObject("list1",list1);
        mv.addObject("list2",list2);
        mv.addObject("list3",list3);
//        System.out.println("结果："+list1);
        mv.setViewName("fpga_upfile");
        return mv;

    }



    /*
     *修改用户信息(OK)
     */
    @RequestMapping("updatemsg")
    public String updatemsg(@RequestParam("username") String username,@RequestParam("tel") String tel,@RequestParam("sex") String sex,@RequestParam("age") String age) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("username", username);
        map.put("sex", sex);
        map.put("tel", tel);
        map.put("age", age);
        userService.updateUser(map);
        return "fpga_main";
    }


    /*
     *密码修改(OK)
     */
    @RequestMapping("toupdate")
    public String updatepassword(@RequestParam("newpassword") String password, @RequestParam("username") String username) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("username", username);
        map.put("password", password);
        userService.updatePassword(map);
        return "fpga_main";
    }
    /*
     *连接服务器
     */


    /*
     *本地文件上传
     * 上传文件暂放D:\images
     */
    @RequestMapping(value = "/gotoAction", method = RequestMethod.POST)
    public ModelAndView upload(ModelAndView mv, @RequestParam("file") MultipartFile file,
                               HttpServletRequest request) {

        if (!file.isEmpty()) {

            String contextPath = request.getContextPath();//"/SpringMvcFileUpload"
            String servletPath = request.getServletPath();//"/gotoAction"
            String scheme = request.getScheme();//"http"


            String storePath = "D:\\images";//存放我们上传的文件路径

            String fileName = file.getOriginalFilename();

            File filepath = new File(storePath, fileName);
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();//如果目录不存在，创建目录

            }

            try {
                file.transferTo(new File(storePath + File.separator + fileName));//把文件写入目标文件地址
            } catch (Exception e) {

                e.printStackTrace();
                mv.addObject("message", "文件上传失败，请重新上传");
                mv.setViewName("fpga_upfile");
                return mv;

            }
            mv.addObject("message", "文件上传成功，可以开始实验。");
            mv.setViewName("fpga_test");
            return mv;

        } else {
            mv.addObject("message", "文件上传失败，请重新上传");
            mv.setViewName("fpga_upfile");
            return mv;//返回到失败的页面
        }

    }

    /*
     *文件下载
     */
    @RequestMapping(value = "/download", method = RequestMethod.GET) //匹配的是href中的download请求
     public ResponseEntity<byte[]> download(HttpServletRequest request, @RequestParam("filename") String filename,
                                           Model model) throws IOException {

        String downloadFilePath = "D:\\images";//从我们的上传文件夹中去取

        File file = new File(downloadFilePath + File.separator + filename);//新建一个文件

        HttpHeaders headers = new HttpHeaders();//http头信息

        String downloadFileName = new String(filename.getBytes("UTF-8"), "iso-8859-1");//设置编码

        headers.setContentDispositionFormData("attachment", downloadFileName);

        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        //MediaType:互联网媒介类型  contentType：具体请求中的媒体类型信息

        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);

    }


}
